<?php

/**
 * 数据操作
 *
 * php /path/aishang/index.php top auto
 *
 * @author 
 */
if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}
include_once APPPATH . "libraries/ExceptionHandler.php";
include_once APPPATH . "core/base_controller.php";
class jd extends base_controller {

    var $taobaoclient = null;

    public function __construct() {
        parent::__construct();
        $this->load->model('authorizetokenmodel'); //授权表
        $this->load->model('pushsettingmodel');
        $this->load->model('ordermodel', 'apachorder');
        $this->load->model('detailmodel', 'apachdetail');
        $this->load->library('ApachSdk');
        $this->load->library('queue', array('key'=>'jdong_queue')); //队列
    }

    /**
     * 定时读取修改的订单备注
     */
    public function cronRemark() {
        set_time_limit(0);
        $page = 1;
        $totalpages = 0;
        $startTime = date("Y-m-d H:i:s", strtotime('-5 day'));
        $endTime = date("Y-m-d H:i:s");
        //程序已在运行中即退出
        $running_log = APPPATH . "logs/jd.cronRemark.run.lock";
        if (file_exists($running_log)) {
            return;
        }
        //创建运行锁
        file_put_contents($running_log, '1');
        $auths = $this->authorizetokenmodel->getSellersByChannel(2);
        foreach ($auths as $auth) {
            try {
                if (!$auth['full_token']) {
                    continue;
                }
                $token = $auth['full_token'] ? unserialize($auth['full_token']) : null;
                if ($token) {
                    $this->jdclient = new JDClient(array($token));
                    $this->orderapi = new OrderAPI(array($this->jdclient));
                    //记录读取时间
                    $log_last_run_file = APPPATH . "logs/" . $token->vender_id . ".remarkruntime.log";
                    if (file_exists($log_last_run_file)) {
                        $text = file_get_contents($log_last_run_file);
                        $t = unserialize($text);
                        if (isset($t['endTime'])) {
                            $diff_time = time() - strtotime($t['endTime']);
                            if ($diff_time > 5184000) {
                                $t['endTime'] = date("Y-m-d", strtotime("-60 day")) . " 23:59:59";
                            }
                            $startTime = $t['endTime'];
                            $endTime = date('Y-m-d H:i:s');
                        }
                    }
                    //按时间分页读取数据
                    $output = '';
                    do {
                        $rs = $this->orderapi->getRemarkByModifyTime($startTime, $endTime, $page);
                        if (isset($rs['remarkList']) && $rs['remarkList']) {
                            $odata = $rs['remarkList'];
                            $ototal = $rs['totleNum'];
                            foreach ($odata as $v) {
                                $seristr = serialize(array('order_id' => $v['orderId'], 'user_id' => $auth["user_id"]));
                                $this->queue->push($seristr);
                                $output.=$seristr . "\n";
                            }
                            $totalpages = ceil($ototal / 100); //默认pagesize是100
                            //记录拉取时间
                            if ($output) {
                                echo "modifyremark->start:" . $startTime . '---' . $endTime . "|" . $page . "\n";
                                echo $output;
                                file_put_contents($log_last_run_file, serialize(array('startTime' => $startTime, 'endTime' => $endTime)));
                                echo "modifyremark->end \n";
                            }
                        }
                        $page++;
                    } while (($page - 1) < $totalpages);
                    $page = 1;
                    $totalpages = 0;
                    unset($this->jdclient);
                    unset($this->orderapi);
                    unset($token);
                }
                sleep(5);
            } catch (Exception $e) {
                echo 'Caught exception: ', $e->getMessage(), "\n";
            }
        }

        unlink($running_log);
        echo "unlink log \n";
    }

    /**
     * 定时读取添加订单备注
     */
    public function cronCreateRemark() {
        set_time_limit(0);
        $page = 1;
        $totalpages = 0;
        $startTime = date("Y-m-d H:i:s", strtotime('-5 day'));
        $endTime = date("Y-m-d H:i:s");
        //程序已在运行中即退出
        $running_log = APPPATH . "logs/jd.cronCreateRemark.run.lock";
        if (file_exists($running_log)) {
            return;
        }
        //创建运行锁
        file_put_contents($running_log, '1');
        $auths = $this->authorizetokenmodel->getSellersByChannel(2);
        foreach ($auths as $auth) {
            try {
                if (!$auth['full_token']) {
                    continue;
                }
                $token = $auth['full_token'] ? unserialize($auth['full_token']) : null;
                if ($token) {
                    $this->jdclient = new JDClient(array($token));
                    $this->orderapi = new OrderAPI(array($this->jdclient));
                    //记录读取时间
                    $log_last_run_file = APPPATH . "logs/" . $token->vender_id . ".createremarkruntime.log";
                    if (file_exists($log_last_run_file)) {
                        $text = file_get_contents($log_last_run_file);
                        $t = unserialize($text);
                        if (isset($t['endTime'])) {
                            $diff_time = time() - strtotime($t['endTime']);
                            if ($diff_time > 5184000) {
                                $t['endTime'] = date("Y-m-d", strtotime("-60 day")) . " 23:59:59";
                            }
                            $startTime = $t['endTime'];
                            $endTime = date('Y-m-d H:i:s');
                        }
                    }
                    //按时间分页读取数据
                    $output = '';
                    do {
                        $rs = $this->orderapi->getRemarkByCreateTime($startTime, $endTime, $page);
                        if (isset($rs['remarkList']) && $rs['remarkList']) {
                            $odata = $rs['remarkList'];
                            $ototal = $rs['totleNum'];
                            foreach ($odata as $v) {
                                $seristr = serialize(array('order_id' => $v['orderId'], 'user_id' => $auth["user_id"]));
                                $this->queue->push($seristr);
                                $output.=$seristr . "\n";
                            }
                            $totalpages = ceil($ototal / 100); //默认pagesize是100
                            //记录拉取时间
                            if ($output) {
                                echo "createremark->start:" . $startTime . '---' . $endTime . "|" . $page . "\n";
                                echo $output;
                                file_put_contents($log_last_run_file, serialize(array('startTime' => $startTime, 'endTime' => $endTime)));
                                echo "createremark->end \n";
                            }
                        }
                        $page++;
                    } while (($page - 1) < $totalpages);
                    $page = 1;
                    $totalpages = 0;
                    unset($this->jdclient);
                    unset($this->orderapi);
                    unset($token);
                }
                sleep(5);
            } catch (Exception $e) {
                echo 'Caught exception: ', $e->getMessage(), "\n";
            }
        }
        unlink($running_log);
        echo "unlink log \n";
    }

    /**
     * 定时读取最近修改过的订单,入队列
     */
    public function cronModifyTime() {
        set_time_limit(0);
        $page = 1;
        $pageSize = 100;
        $totalpages = 0;
        $startTime = date("Y-m-d H:i:s", strtotime('-5 day'));
        $endTime = date("Y-m-d H:i:s");
        //程序已在运行中即退出
        $running_log = APPPATH . "logs/jd.cronModify.run.lock";
        if (file_exists($running_log)) {
            return;
        }
        //创建运行锁
        file_put_contents($running_log, '1');
        $auths = $this->authorizetokenmodel->getSellersByChannel(2);
        foreach ($auths as $auth) {
            try {
                if (!$auth['full_token']) {
                    continue;
                }
                $token = $auth['full_token'] ? unserialize($auth['full_token']) : null;
                echo $auth["user_id"] . "\n";
                if ($token) {
                    $this->jdclient = new JDClient(array($token));
                    $this->orderapi = new OrderAPI(array($this->jdclient));
                    //记录读取时间
                    $log_last_run_file = APPPATH . "logs/" . $token->vender_id . ".modifyruntime.log";
                    if (file_exists($log_last_run_file)) {
                        $text = file_get_contents($log_last_run_file);
                        $t = unserialize($text);
                        if (isset($t['endTime'])) {
                            $diff_time = time() - strtotime($t['endTime']);
                            if ($diff_time > 5184000) {
                                $t['endTime'] = date("Y-m-d", strtotime("-60 day")) . " 23:59:59";
                            }
                            $startTime = $t['endTime'];
                            $endTime = date('Y-m-d H:i:s');
                        }
                    }
                    //按时间分页读取数据
                    $output = '';
                    do {
                        $rs = $this->orderapi->getOrderByModifyTime($startTime, $endTime, $page, $pageSize);
                        print_r($rs);
                        if (isset($rs['order_info_list']) && $rs['order_info_list']) {
                            $odata = $rs['order_info_list'];
                            $ototal = $rs['order_total'];
                            foreach ($odata as $v) {
                                $seristr = serialize(array('order_id' => $v['order_id'], 'user_id' => $auth["user_id"]));
                                $this->queue->push($seristr);
                                $output.=$seristr . "\n";
                            }
                            $totalpages = ceil($ototal / $pageSize); //默认pagesize是100
                            //记录拉取时间
                            if ($output) {
                                echo "ordersearch->start:" . $startTime . '---' . $endTime . "|" . $page . "\n";
                                echo $output;
                                file_put_contents($log_last_run_file, serialize(array('startTime' => $startTime, 'endTime' => $endTime)));
                                echo "ordersearch->end \n";
                            }
                        }
                        $page++;
                    } while (($page - 1) < $totalpages);
                    $page = 1;
                    $totalpages = 0;
                    unset($this->jdclient);
                    unset($this->orderapi);
                    unset($token);
                }
                sleep(5);
            } catch (Exception $e) {
                echo 'Caught exception: ', $e->getMessage(), "\n";
            }
        }
        unlink($running_log);
        echo "unlink log \n";
    }

    /*
     *  消费队列订单消息
     *  add by tongxiaoyong     
     */
    public function consumption() {
        set_time_limit(0);
        $sleep_time = 5000; //处理队列延时
        #开启个推送队列
        $wait_pushed_queue = new Queue(array('key'=>'wait_push_queue'));
        while (true) {
            try {
                $seri_str = $this->queue->pop();
                if (!$seri_str) {
                    usleep($sleep_time);
                    continue;
                }
                echo $seri_str . "\n";
                $queue = unserialize($seri_str);
                if (!$queue || !isset($queue['order_id']) || !isset($queue['user_id'])) {
                    usleep($sleep_time);
                    continue;
                }
                $getToken = $this->authorizetokenmodel->getToken($queue['user_id'], 2);
                if (!isset($getToken->full_token) || !$getToken->full_token) {
                    usleep($sleep_time);
                    continue;
                }
                $token = unserialize($getToken->full_token);
                if ($token) {
                    $this->jdclient = new JDClient(array($token));
                    if ($this->jdclient) {
                        $this->orderapi = new OrderAPI(array($this->jdclient));
                        $this->wareapi = new WareAPI(array($this->jdclient));
                        $rs = $this->orderapi->getOrderByTid($queue['order_id']);
                        foreach ($rs as $orderinfo) {
                            if (!isset($orderinfo['order_id']))
                                break;
                            $orderinfo['user_id'] = $queue['user_id'];
                            //有flag的直接读取,没有读取备注接口
                            if (isset($queue['flag'])) {
                                $orderinfo['id_remark'] = $queue['flag'];
                            } else {
                                $vark = $this->orderapi->queryVenderRemarkByOrderId($orderinfo['order_id']);
                                if (isset($vark['vender_remark']['flag'])) {
                                    $orderinfo['id_remark'] = $vark['vender_remark']['flag'];
                                }
                            }
                            foreach ($orderinfo['item_info_list'] as &$item) {
                                $item['sku_image'] = '';
                                $sku = $this->orderapi->findSkuById($item['sku_id']);
                                $item['sku_image'] = 'http://img10.360buyimg.com/n2/'.$sku['logo'];
                                echo $orderinfo['order_id'] . "->" . $item['sku_id'] . "->" . $item['sku_image'] . "\n";
                            }
                            //配送时间设置
                            $pushSetting = $this->pushsettingmodel->getPushSetting($getToken->huaji_user_id);
                            if($pushSetting){
                                switch($pushSetting->delivery_usually_time){
                                    case "1":
                                        $orderinfo['deadline'] = $orderinfo['payment_confirm_time'];
                                        break;
                                    case "2":
                                        $orderinfo['deadline'] = date('Y-m-d H:i:s',strtotime($orderinfo['payment_confirm_time'])+86400);
                                        break;
                                    case "3":
                                        $orderinfo['deadline'] = $pushSetting->delivery_custom;
                                        break;
                                }
                            }
                            if(!isset($orderinfo['deadline']) || strpos($orderinfo['deadline'],'0001') !== false){
                                $orderinfo['deadline'] = '';    
                            }
                            //保存到本地数据库
                            $this->apachorder->newjdOrderInfo($orderinfo);
                            foreach ($orderinfo['item_info_list'] as $item) {
                                $this->apachdetail->newjdItemInfo($orderinfo['order_id'], $item);
                            }
                            //大于0自动推送订单
                            if(isset($pushSetting->push_time) && $pushSetting->push_time > 0){
                                $push_time = date('Y-m-d H:i:s',time()+$pushSetting->push_time*60);
                                $wait_pushed_queue->push(serialize(array(
                                    'order_id' => $queue['order_id'],
                                    'huaji_user_id' => $getToken->huaji_user_id,
                                    'user_id' => $queue['user_id'],
                                    'push_time' => $push_time
                                )));
                            }
                            //通知新订单
                            $notice_queue = new Queue(array('key'=>'ordermessage'.$getToken->huaji_user_id));
                            $notice_queue->pop();
                            $notice_queue->push('{"num":1}');
                        }
                    }
                }
            } catch (Exception $e) {
                echo 'Caught exception: ', $e->getMessage(), "\n";
                if(strpos($e->getMessage(),'code:19') !== false){
                    $this->authorizetokenmodel->edit($queue['user_id'],array('catch_failed_info'=>'token失效,生新授权','catch_failed_time'=>date('Y-m-d H:i:s')));
                }elseif(strpos($e->getMessage(),'code:2') !== false){
                    $this->authorizetokenmodel->edit($queue['user_id'],array('catch_failed_info'=>'接口访问次数超出限制','catch_failed_time'=>date('Y-m-d H:i:s')));
                }
                $this->queue->push($seri_str);
            }
            usleep($sleep_time);
        }
    }

    function _getPropImages($ware_id, $attributes, $page = 1) {
        $skuimgs = $this->orderapi->getWareMainByID($ware_id, $page);
        foreach ($skuimgs as $v) {
            if (!empty($attributes)) {
                if (strpos($attributes, $v['color_id']) !== false) {
                    return $v['img_url'];
                }
            } else {
                if ($v['is_main'] == "是") {
                    return $v['img_url'];
                }
            }
        }
        $page++;
        if ($page < 10)
            return $this->_getPropImages($ware_id, $attributes, $page);
    }
    
    
    /*
     *  消费队列订单消息
     *  add by tongxiaoyong     
     */
    public function test() {
        set_time_limit(0);
        $sleep_time = 5000; //处理队列延时
        #开启个推送队列
        $wait_pushed_queue = new Queue(array('key'=>'wait_push_queue'));
            try {
                $seri_str = $this->queue->pop();
                if (!$seri_str) {
                    usleep($sleep_time);
                }
                echo $seri_str . "\n";
                $queue = unserialize($seri_str);
                if (!$queue || !isset($queue['order_id']) || !isset($queue['user_id'])) {
                    usleep($sleep_time);
                }
                $getToken = $this->authorizetokenmodel->getToken($queue['user_id'], 2);
                if (!isset($getToken->full_token) || !$getToken->full_token) {
                    usleep($sleep_time);
                }
                $token = unserialize($getToken->full_token);
                if ($token) {
                    $this->jdclient = new JDClient(array($token));
                    if ($this->jdclient) {
                        $this->orderapi = new OrderAPI(array($this->jdclient));
                        $this->wareapi = new WareAPI(array($this->jdclient));
                        $rs = $this->orderapi->getOrderByTid($queue['order_id']);
                        foreach ($rs as $orderinfo) {
                            if (!isset($orderinfo['order_id']))
                                break;
                            $orderinfo['user_id'] = $queue['user_id'];
                            //有flag的直接读取,没有读取备注接口
                            if (isset($queue['flag'])) {
                                $orderinfo['id_remark'] = $queue['flag'];
                            } else {
                                $vark = $this->orderapi->queryVenderRemarkByOrderId($orderinfo['order_id']);
                                if (isset($vark['vender_remark']['flag'])) {
                                    $orderinfo['id_remark'] = $vark['vender_remark']['flag'];
                                }
                            }
                            foreach ($orderinfo['item_info_list'] as &$item) {
                                $item['sku_image'] = '';
                                $sku = $this->orderapi->findSkuById($item['sku_id']);
                                $item['sku_image'] = 'http://img10.360buyimg.com/n2/'.$sku['logo'];
                                echo $orderinfo['order_id'] . "->" . $item['sku_id'] . "->" . $item['sku_image'] . "\n";
                            }
                        }
                    }
                }
            } catch (Exception $e) {
                echo 'Caught exception: ', $e->getMessage(), "\n";
            }
    }
}
